
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>微信支付ODY</title>
</head>

<body>
  <script>
    if (typeof WeixinJSBridge == "undefined") {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
      }
    } else {
      onBridgeReady();
    }

    /**
     * [onBridgeReady 支付业务逻辑]
     * @return {[type]} [description]
     */
    function onBridgeReady() {
      let queryObj = getQuery(),
      appId = queryObj.appId,
      timeStamp = queryObj.timeStamp,
      nonceStr = queryObj.nonceStr,
      prepayId = queryObj.prepayId,
      paySign = queryObj.paySign,
      url = queryObj.url;

      if (url.indexOf('pay-success')>-1) {
        errorUrl = url.replace('pay-success', 'pay-fail');
        // 修改支付失败跳转路径
        if(queryObj.version==='3.0.0'){
          errorUrl = url.replace('pay-success', 'cashier');
        }
      } else {
        errorUrl = url.replace(url, url+'?status=fail');
      }

      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          "appId": appId, // 公众号名称，由商户传入
          "timeStamp": timeStamp, // 时间戳，自1970年以来的秒数
          "nonceStr": nonceStr, // 随机串
          "package": `prepay_id=${prepayId}`,
          "signType": "MD5", // 微信签名方式：
          "paySign": paySign // 微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            location.href = url;
          } else {
            let errMap = {
              'get_brand_wcpay_request:cancel': '支付过程中用户取消',
              'get_brand_wcpay_request:fail': '支付失败'
            };
            let errMsg = errMap[res.err_msg] || '支持出现未知错误';

            alert(errMsg);
            location.href = errorUrl;
          }
        });
    }

    /**
     * [getQuery 获取url传入参数]
     * @return {[type]} [description]
     */
    function getQuery() {
      var url = location.search; //获取url中"?"符后的字串
      var rtv = {};

      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var queryGroup = str.split("&");

        queryGroup.forEach(query => {
          let [ key, val ] = query.split("=");
          rtv[key] = unescape(val);
        });
      }
      return rtv;
    }

  </script>
</body>

</html>
